﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO.Compression;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Drawing;
using RecruitStudents.Utility.Json;
using Hxj.Data;

namespace RecruitStudents.Utility
{
    /// <summary>
    /// 系统常用类,类型转换帮助类
    /// </summary>
    public static class ConvertHelper
    {
        /// <summary>
        /// 转换数据类型
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static TResult ConvertValue<TResult>(this object value)
        {
            if (Convert.IsDBNull(value) || value == null)
                return default(TResult);

            object obj = ConvertValue(typeof(TResult), value);
            if (obj == null)
            {
                return default(TResult);
            }
            return (TResult)obj;
        }
        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static object ConvertValue(Type type, object value)
        {
            if (Convert.IsDBNull(value) || (value == null))
            {
                return null;
            }
            Type type2 = value.GetType();
            if (type == type2)
            {
                return value;
            }
            if (((type == typeof(Guid)) || (type == typeof(Guid?))) && (type2 == typeof(string)))
            {
                if (string.IsNullOrEmpty(value.ToString()))
                {
                    return null;
                }
                return new Guid(value.ToString());
            }
            if (((type == typeof(DateTime)) || (type == typeof(DateTime?))) && (type2 == typeof(string)))
            {
                if (string.IsNullOrEmpty(value.ToString()))
                {
                    return null;
                }
                return Convert.ToDateTime(value);
            }
            if (type.IsEnum)
            {
                try
                {
                    return Enum.Parse(type, value.ToString(), true);
                }
                catch
                {
                    return Enum.ToObject(type, value);
                }
            }
            if ((type == typeof(bool)) || (type == typeof(bool?)))
            {
                bool result = false;
                if (bool.TryParse(value.ToString(), out result))
                {
                    return result;
                }
                //处理  Request.Form  的 checkbox  如果没有返回值就是没有选中false  
                if (string.IsNullOrEmpty(value.ToString()))
                {
                    return false;
                }
                return true;
            }
            if (type.IsGenericType)
            {
                type = type.GetGenericArguments()[0];
            }
            return Convert.ChangeType(value, type);
        }
        /// <summary>
        /// 获取当前时间(带时分秒)
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNowDateTime()
        {
            return DateTime.Now;
        }
        /// <summary>
        /// 获取当前时间(不带时分秒,时分秒全为零)
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNowDate()
        {
            return DateTime.Now.Date;
        }


        #region ========设置文本框只读========
        /// <summary>
        /// 设置文本框只读
        /// </summary>
        /// <param name="txt"></param>
        public static void ToReadOnly(params HtmlInputText[] txts)
        {
            foreach (HtmlInputText txt in txts)
            {
                txt.ToReadOnly();
            }
        }
        /// <summary>
        /// 设置文本框只读
        /// </summary>
        /// <param name="txt"></param>
        public static void ToReadOnly(this HtmlInputText txt)
        {
            txt.Attributes.Add("ReadOnly", "ReadOnly");
        }
        /// <summary>
        /// 设置文本框只读
        /// </summary>
        /// <param name="txt"></param>
        public static void ToReadOnly(params TextBox[] txts)
        {
            foreach (TextBox txt in txts)
            {
                txt.ToReadOnly();
            }
        }
        /// <summary>
        /// 设置文本框只读
        /// </summary>
        /// <param name="txt"></param>
        public static void ToReadOnly(this TextBox txt)
        {
            txt.Attributes.Add("ReadOnly", "ReadOnly");
        }
        #endregion

        #region ========Convert========
        /// <summary>
        /// 将已经为在URL中传输而编码的字符串转换为解码的字符串。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToUrlDecode(this string value)
        {
            return System.Web.HttpUtility.UrlDecode(value);
        }
        /// <summary>
        /// 对 URL 字符串进行编码。
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToUrlEncode(this string value)
        {
            return System.Web.HttpUtility.UrlEncode(value);
        }
        /// <summary>
        /// 获取Guid
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Guid ToSafeGuid(this object value)
        {
            if (value == null)
            {
                return Guid.Empty;
            }
            Guid mGuid = new Guid(value.ToString());
            return mGuid;
        }
        /// <summary>
        /// 获取Guid
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Guid ToSafeGuid(this string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return Guid.Empty;
            }
            Guid mGuid = new Guid(value);
            return mGuid;
        }
        /// <summary>
        /// 获得安全字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToSafeString(this string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }

            return value.Trim();
        }
        /// <summary>
        /// 获得安全字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToSafeString(this object value)
        {
            if (value == null)
            {
                return string.Empty;
            }

            return value.ToString().Trim();
        }
        /// <summary>
        /// 获得安全字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToSafeInt(this object value)
        {
            if (value == null)
            {
                return 0;
            }
            return ToSafeInt(value.ToSafeString());
        }
        /// <summary>
        /// 获得安全小数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal ToSafeDecimal(this object value)
        {
            if (value == null)
            {
                return 0.0m;
            }
            return ToSafeDecimal(value.ToSafeString());
        }
        /// <summary>
        /// 获得安全小数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal ToSafeDecimal(this decimal? value)
        {
            return value.HasValue ? value.Value : 0.0m;
        }
        /// <summary>
        /// 获得安全小数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal ToSafeDecimal(this string value)
        {
            decimal rtn = 0.0m;
            if (value.IsNullOrEmptyString())
            {
                return rtn;
            }
            decimal.TryParse(value, out rtn);
            return rtn;
        }
        /// <summary>
        /// 获得安全Bool
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool ToSafeBool(this bool? value)
        {
            return value.HasValue ? value.Value : false;
        }
        /// <summary>
        /// 获得安全整型数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToSafeInt(this int? value)
        {
            return value.HasValue ? value.Value : 0;
        }
        /// <summary>
        /// 获得安全整型数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToSafeInt(this string value)
        {
            int rtn = 0;

            if (value.IsNullOrEmptyString())
            {
                return rtn;
            }
            int.TryParse(value, out rtn);
            return rtn;
        }
        /// <summary>
        /// 获得安全整型数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long ToSafeLong(this long? value)
        {
            return value.HasValue ? value.Value : 0;
        }
        /// <summary>
        /// 获得安全整型数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long ToSafeLong(this string value)
        {
            long rtn = 0;

            if (value.IsNullOrEmptyString())
            {
                return rtn;
            }
            long.TryParse(value, out rtn);
            return rtn;
        }
        /// <summary>
        /// 是否是日期格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsDateTime(this string value)
        {
            DateTime rtn = DateTime.MinValue;
            return DateTime.TryParse(value, out rtn);
        }
        /// <summary>
        /// 获得安全日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ToSafeDateTime(this string value)
        {
            DateTime rtn = DateTime.MinValue;
            if (value.IsNullOrEmptyString())
            {
                return rtn;
            }
            DateTime.TryParse(value, out rtn);
            return rtn;
        }
        /// <summary>
        /// 获得安全日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime ToSafeDateTime(this DateTime? value)
        {
            return value.HasValue ? value.Value : DateTime.MinValue;
        }
        /// <summary>
        /// 转换为整数字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToIntString(this decimal value)
        {
            return value.ToString("0");
        }
        /// <summary>
        /// 转换为整数字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToIntString(this int value)
        {
            return value.ToString("0");
        }
        /// <summary>
        /// 转换为整数字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToDecimalString(this decimal value)
        {
            return value.ToString("0.00");
        }
        /// <summary>
        /// 时间转换为日期字符串
        /// </summary> 
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyyMMdd(this DateTime value)
        {
            if (value == DateTime.MinValue)
            {
                return string.Empty;
            }

            return value.ToString("yyyyMMdd");
        }
        /// <summary>
        /// 时间转换为日期字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyy_MM_dd_HH_mm(this DateTime value)
        {
            if (value == DateTime.MinValue)
            {
                return string.Empty;
            }

            return value.ToString("yyyy-MM-dd HH:mm");
        }
        /// <summary>
        /// 时间转换为日期字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyy_MM_dd(this DateTime value)
        {
            if (value == DateTime.MinValue)
            {
                return string.Empty;
            }

            return value.ToString("yyyy-MM-dd");
        }
        /// <summary>
        /// 时间转换为时间字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyyMMddHHmmss(this DateTime value)
        {
            if (value == DateTime.MinValue)
            {
                return string.Empty;
            }

            return value.ToString("yyyyMMddHHmmss");
        }
        /// <summary>
        /// 时间转换为时间字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyy_MM_dd_HH_mm_ss(this DateTime value)
        {
            if (value == DateTime.MinValue)
            {
                return string.Empty;
            }

            return value.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 时间转换为时间字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyy_MM_dd_HH_mm_ss(this DateTime? value)
        {
            return value.ToSafeDateTime().ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 时间转换为时间字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string DateTimeToyyyy_MM_dd(this DateTime? value)
        {
            return value.ToSafeDateTime().ToString("yyyy-MM-dd");
        }
        /// <summary>
        /// 日期字符串转换为日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime yyyyMMddToDate(this string value)
        {
            // 特殊判断
            if (value == "00000000")
            {
                return DateTime.MinValue;
            }
            else if (value == "99999999")
            {
                return DateTime.MaxValue;
            }

            return DateTime.ParseExact(value, "yyyyMMdd", null);
        }
        /// <summary>
        /// 时间字符串转换为时间
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static DateTime yyyyMMddHHmmssToDate(this string value)
        {
            return DateTime.ParseExact(value, "yyyyMMddHHmmss", null);
        }
        /// <summary>
        /// 布尔字符串转换为布尔
        /// </summary>
        /// <param name="value">字符串</param>
        /// <returns></returns>
        public static bool ToSafeBool(this string value)
        {
            bool rtn = false;
            if (value.IsNullOrEmptyString())
            {
                return rtn;
            }
            bool.TryParse(value, out rtn);
            return rtn;
        }
        /// <summary>
        /// 判断字符串是否相等,忽略大小写
        /// </summary>
        /// <param name="value">输入的字符串</param>
        /// <param name="strInValue">被检查的字符串</param>
        /// <returns></returns>
        public static bool ToEquals(this string value, string strInValue)
        {
            return string.Equals(value, strInValue, StringComparison.CurrentCultureIgnoreCase);
        }
        /// <summary>
        /// 字符串替换
        /// </summary>
        /// <param name="value"></param>
        /// <param name="strOld"></param>
        /// <param name="strNew"></param>
        /// <returns></returns>
        public static string ToReplace(this string value, string strOld = "", string strNew = "")
        {
            if (value == null || value.IsNullOrEmptyString())
            {
                return string.Empty;
            }
            if (strOld == "")
            {
                return value.ToReplace("'", "").Replace("\r\n", "");
            }
            return value.Replace(strOld, strNew);
        }

        /// <summary>
        /// 将DataTable转换成Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToJson(this DataTable dt)
        {
            return JsonHelper.DataTableToJson(dt);
        }

        /// <summary>
        /// 将Json数据转换成DataTable
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(this string strJson)
        {
            return JsonHelper.ToDataTable(strJson);
        }

        /// <summary>
        /// 将List转换成Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToJson<T>(this T list)
        {
            return JsonHelper.JsonSerializer<T>(list);
        }

        /// <summary>
        /// 将Json数据转换成List
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T ToList<T>(this string strJson)
        {
            return JsonHelper.JsonDeserialize<T>(strJson);
        }


        #endregion

        #region ========字符串是否为空或null========
        /// <summary>
        /// 字符串是否为空或null
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNullOrEmptyString(this string value)
        {
            return string.IsNullOrEmpty(value);
        }
        #endregion

        #region ========去除Sql注入========
        /// <summary>
        /// 扩展方法，去除SQL注入字符串
        /// </summary>
        /// <param name="value">字符串</param>
        /// <returns>去除SQL注入字符串</returns>
        public static string RemoveSqlInjection(this string value)
        {
            if (value == null)
            {
                return string.Empty;
            }

            value = value.Replace("'", "''");

            //检测攻击性危险字符串
            string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
            string[] testArray = testString.Split('|');
            foreach (string testStr in testArray)
            {
                if (value.ToLower().IndexOf(testStr) != -1)
                {
                    //检测到攻击字符串,清空传入的值
                    value = "";
                }
            }

            return value;
        }
        #endregion

        #region ========截取字符串长度,用省略号截取========
        /// <summary>
        /// 截取字符串长度,用省略号截取
        /// </summary>
        /// <param name="value"></param>
        /// <param name="left"></param>
        /// <returns></returns>
        public static string ToLeft(this string value, int left)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }
            if (value.Length > left)
            {
                return value.Substring(0, left) + "...";
            }
            return value;
        }
        #endregion

        #region ========生成0-9随机数========
        /// <summary>
        /// 生成0至9的随机数
        /// </summary>
        /// <param name="VcodeNum">生成长度</param>
        /// <param name="IsWirteCook">是否写入Session</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            Random rnd = new Random();
            StringBuilder sb = new StringBuilder(VcodeNum);
            int i = 1;
            while (i <= VcodeNum)
            {
                sb.Append(rnd.Next(9));
                i++;
            }
            return sb.ToString();
        }
        #endregion


        private const string strKey = "GAP";


        #region ========加密========
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string ToSafeEncrypt(this string Text)
        {
            return Encrypt(Text);
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, strKey);
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        private static string Encrypt(string Text, string sKey)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                try
                {

                    byte[] inputByteArray;
                    inputByteArray = Encoding.Default.GetBytes(Text);
                    des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                    des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Dispose();
                    StringBuilder ret = new StringBuilder();
                    foreach (byte b in ms.ToArray())
                    {
                        ret.AppendFormat("{0:X2}", b);
                    }
                    return ret.ToString();
                }
                finally
                {
                    ms.Dispose();
                    des.Clear();
                }
            }
        }
        #endregion

        #region ========解密========
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string ToSafeDecrypt(this string Text)
        {
            return Decrypt(Text);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, strKey);
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        private static string Decrypt(string Text, string sKey)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                try
                {
                    int len;
                    len = Text.Length / 2;
                    byte[] inputByteArray = new byte[len];
                    int x, i;
                    for (x = 0; x < len; x++)
                    {
                        i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                        inputByteArray[x] = (byte)i;
                    }
                    des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                    des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Dispose();
                    return Encoding.Default.GetString(ms.ToArray());
                }
                finally
                {
                    des.Clear();
                    ms.Dispose();
                }
            }
        }
        #endregion

        #region  ========读写Cookie========
        /// <summary>
        /// 写Cookie值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="strCookieName">Cookie名称</param>
        /// <param name="strCookieValue">Cookie值</param>
        public static void WriteCookie(HttpContext context, string strCookieName, string strCookieValue)
        {
            HttpCookie cookie = new HttpCookie("SystemCookie");
            cookie.Values[strCookieName] = strCookieValue;
            cookie.Expires = DateTime.MaxValue;
            context.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 获取Cookie值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="strCookieName">Cookie名称</param>
        /// <returns></returns>
        public static string GetCookieValue(HttpContext context, string strCookieName)
        {
            HttpCookie cookie = context.Request.Cookies["SystemCookie"];
            if (cookie != null)
            {
                return cookie[strCookieName];
            }
            return string.Empty;
        }
        #endregion


        #region 生产图片
        /// <summary>
        /// 生产图片
        /// </summary>
        /// <param name="context"></param>
        public static void GenImg(HttpContext context, string checkCode)
        {
            using (Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 23))
            {
                using (Graphics g = Graphics.FromImage(image))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        g.Clear(Color.White);
                        using (Font font = new Font("Arial", 14, (FontStyle.Italic)))
                        {
                            using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Black, 1.2f, true))
                            {
                                g.DrawString(checkCode, font, brush, 1, 1);
                                image.Save(ms, ImageFormat.Gif);
                                brush.Dispose();
                            }
                            font.Dispose();
                        }
                        context.Response.BinaryWrite(ms.ToArray());
                        ms.Dispose();
                    }
                    g.Dispose();
                }
                image.Dispose();
            }
            context.Response.End();
        }
        #endregion

        /// <summary>
        /// 为列头绘制CheckBox 
        /// </summary> 
        /// <param name="view">GridView</param> 
        /// <param name="checkItem">RepositoryItemCheckEdit</param> 
        /// <param name="fieldName">需要绘制Checkbox的列名</param> 
        /// <param name="e">ColumnHeaderCustomDrawEventArgs</param> 
        public static void DrawHeaderCheckBox(this DevExpress.XtraGrid.Views.Grid.GridView view, RepositoryItemCheckEdit checkItem, string fieldName, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName.Equals(fieldName))
            {
                e.Column.Caption = " ";
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                if (view.DataRowCount == 0)
                {
                    DrawCheckBox(checkItem, e.Graphics, e.Bounds, false);
                }
                else
                {
                    DrawCheckBox(checkItem, e.Graphics, e.Bounds, getCheckedCount(view, fieldName) == view.DataRowCount);
                }
                e.Handled = true;
            }
        }
        private static void DrawCheckBox(RepositoryItemCheckEdit checkItem, Graphics g, Rectangle r, bool Checked)
        {
            CheckEditViewInfo _info;
            CheckEditPainter _painter;
            ControlGraphicsInfoArgs _args;
            _info = checkItem.CreateViewInfo() as CheckEditViewInfo;
            _painter = checkItem.CreatePainter() as CheckEditPainter;
            _info.EditValue = Checked;
            _info.Bounds = r;
            _info.PaintAppearance.ForeColor = Color.Black;
            _info.CalcViewInfo(g);
            _args = new ControlGraphicsInfoArgs(_info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            _painter.Draw(_args);
            _args.Cache.Dispose();
        }
        private static int getCheckedCount(DevExpress.XtraGrid.Views.Grid.GridView view, string filedName)
        {
            int count = 0; for (int i = 0; i < view.DataRowCount; i++)
            {
                object _cellValue = view.GetRowCellValue(i, view.Columns[filedName]);
                if (_cellValue == null) continue;
                if (string.IsNullOrEmpty(_cellValue.ToString().Trim())) continue;
                bool _checkStatus = false;
                if (bool.TryParse(_cellValue.ToString(), out _checkStatus))
                { if (_checkStatus) count++; }
            }
            return count;
        }

        private static void CheckAll(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName)
        {
            for (int i = 0; i < view.DataRowCount; i++)
            {
                view.SetRowCellValue(i, view.Columns[fieldName], true);
            }
        }
        private static void UnChekAll(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName)
        {
            for (int i = 0; i < view.DataRowCount; i++)
            {
                view.SetRowCellValue(i, view.Columns[fieldName], false);
            }
        }
        /// <summary>
        /// 同步列头checkbox与列中checkbox状态
        /// </summary>
        /// <param name="view">GridView</param>
        /// <param name="fieldeName">需要绘制Checkbox的列名</param>
        /// <param name="e">MouseEventArgs</param>
        public static void SyncCheckStatus(this DevExpress.XtraGrid.Views.Grid.GridView view, string fieldeName, System.Windows.Forms.MouseEventArgs e)
        {
            /*说明：
             *在MouseDown事件中使用
             *参考：https://www.devexpress.com/Support/Center/Question/Details/Q354489
             *eg:
             *private void gvLampConfig_MouseDown(object sender, MouseEventArgs e)
             *{
             *GridView _view = sender as GridView;
             *_view.SyncCheckStatus(gcCheckFieldName, e);
             *}
             */
            if (e.Clicks == 1 && e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                view.ClearSorting();
                view.PostEditor();
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo _info;
                Point _pt = view.GridControl.PointToClient(System.Windows.Forms.Control.MousePosition);
                _info = view.CalcHitInfo(_pt);
                //if (_info.InColumn && _info.Column.FieldName.Equals(fieldeName))
                if (view.FocusedColumn.FieldName == fieldeName)
                {
                    if (getCheckedCount(view, fieldeName) == view.DataRowCount)
                    {
                        UnChekAll(view, fieldeName);
                    }
                    else
                    {
                        CheckAll(view, fieldeName);
                    }
                }
            }
        }
    }
}
